import sqlalchemy.exc
from flask import Blueprint, request

from Model.models import ElderlyPersonProfile, db
from Utils.APIResponse import APIResponse

eldly_blue = Blueprint("eldly", __name__)


@eldly_blue.route('/elderly/create', methods=['POST'])
def create_elderly_profile():
    data = request.json
    name = data.get('name')
    age = data.get('age')
    health_info = data.get('health_info')

    if not all([name, age, health_info]):
        return APIResponse.error({'error': 'All fields are required.'})

    new_elderly = ElderlyPersonProfile(name=name, age=age, health_info=health_info)
    db.session.add(new_elderly)
    try:
        db.session.commit()
        return APIResponse.success(message={'message': 'Elderly person profile created successfully.'},
                                   data={'id': new_elderly.id})
    except sqlalchemy.exc.SQLAlchemyError as e:
        db.session.rollback()
        return APIResponse.error({'error': 'Error creating elderly person profile: ' + str(e)}, status_code=500)


@eldly_blue.route('/elderly/list', methods=['GET'])
def list_elderly_profiles():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    elderly_profiles = ElderlyPersonProfile.query.paginate(page=page, per_page=per_page, error_out=False)
    data = [{'id': profile.id, 'name': profile.name, 'age': profile.age, 'health_info': profile.health_info} for profile
            in elderly_profiles.items]
    return APIResponse.success(data=data)


@eldly_blue.route('/elderly/update/<int:profile_id>', methods=['PUT'])
def update_elderly_profile(profile_id):
    elderly = ElderlyPersonProfile.query.get(profile_id)
    if not elderly:
        return APIResponse.error({'error': 'Elderly person profile not found.'}, status_code=404)

    data = request.json
    elderly.name = data.get('name', elderly.name)
    elderly.age = data.get('age', elderly.age)
    elderly.health_info = data.get('health_info', elderly.health_info)

    try:
        db.session.commit()
        return APIResponse.success(message={'message': 'Elderly person profile updated successfully.'})
    except sqlalchemy.exc.SQLAlchemyError as e:
        db.session.rollback()
        return APIResponse.error({'error': 'Error updating elderly person profile: ' + str(e)}, status_code=500)


@eldly_blue.route('/elderly/delete/<int:profile_id>', methods=['DELETE'])
def delete_elderly_profile(profile_id):
    elderly = ElderlyPersonProfile.query.get(profile_id)
    if not elderly:
        return APIResponse.error({'error': 'Elderly person profile not found.'}, status_code=404)

    db.session.delete(elderly)
    try:
        db.session.commit()
        return APIResponse.success(message={'message': 'Elderly person profile deleted successfully.'})
    except sqlalchemy.exc.SQLAlchemyError as e:
        db.session.rollback()
        return APIResponse.error({'error': 'Error deleting elderly person profile: ' + str(e)}, status_code=500)
